package com.cwnu.controller;

import com.cwnu.entity.Result;
import com.cwnu.entity.Category;
import com.cwnu.service.CategoryService;
import com.cwnu.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    // 获取文章分类
    @GetMapping
    public Result<List<Category>> getCategory() {
        List<Category> categories = categoryService.getCategory();
        return Result.success(categories);
    }

    // 获取所有文章分类
    @GetMapping("/all")
    public Result<List<Category>> getAllCategory() {
        List<Category> categories = categoryService.getAllCategory();
        return Result.success(categories);
    }
    // 创建类别
    @PostMapping()
    public Result createCategory(String categoryName) {
        // 根据名称和当前用户id在类别表中查询类别
        Integer userId = TokenUtil.getUserId();
        Category category = categoryService.findByNameAndId(categoryName, userId);
        // 未查询到该类别，执行新建操作
        if (category == null) {
            categoryService.createCategory(categoryName);
            return Result.success();
        }
        // 查询到该类别，类别重复
        return Result.error("类别重复，请换一个名称重试！");
    }


    // 修改类别名称
    @PutMapping()
    public Result updateCategory(@RequestParam("oldname") String oldName, @RequestParam("newname") String newName) {
        // 查询当前用户下有没有相同的类别名称
        Integer userId = TokenUtil.getUserId();
        Category category = categoryService.findByNameAndId(newName, userId);
        if (category == null) {
            // 未查询到相同的类别名称，执行修改操作
            categoryService.updateCategory(oldName, newName);
            return Result.success();
        }
        return Result.error("类别名称重复，请重试！");
    }
    // 删除类别
    @DeleteMapping()
    public Result deleteCategory(@RequestParam Integer id) {
        categoryService.deleteCategory(id);
        return Result.success();
    }

}
